import { ref, reactive, watch } from 'vue'
import { useRoute } from 'vue-router'
import dayjs, { Dayjs } from 'dayjs'
import Api from '@/libs/api'
import Enums from '@/datas/Enums'
import { useI18n } from 'vue-i18n'
import { useGoodsBasicInfo } from './useGoodsBasicInfo'
import { useGoodsFreightInfo } from './useGoodsFreightInfo'
import { useGoodsKeywords } from './useGoodsKeywords'
import { useGoodsDebug } from './useGoodsDebug'
import { useGoodsSkuAttributes } from './useGoodsSkuAttributes'
import { useGoodsSkuBatch } from './useGoodsSkuBatch'
import { useGoodsSkuGeneration } from './useGoodsSkuGeneration'
import { useGoodsFormSave } from './useGoodsFormSave'
import type { ApiResponse } from './types'

const initialEditForm = {
	id: 0,
	permissionName: '商品库-商品管理-添加商品',
	attrs: [],
	skus: [],
	spu: {
		numbering: '',
		name: '',
		keywords: [],
		categoryId: '',
		_categoryChainIds: [],
		supplierId: '',
		isSecondHand: false,
		isVirtual: false,
		createdByUser: 0
	},
	salesInfo: {
		sort: 0,
		isPutOnSale: false,
		putOnSaleRange: ref<[Dayjs, Dayjs]>([] as unknown as [Dayjs, Dayjs]),
		isAutoPutOnSale: false,
		isAutoPutOffSale: false
	},
	freightInfo: {
		freightPrice: 0,
		remoteFreights: []
	},
	otherData: {
		isPresentInsurance: false
	},
	copiedById: 0
}

export const useGoodsForm = () => {
	const route = useRoute()
	const { t } = useI18n()

	// 使用分割后的组合式函数
	const { categoryTree, searchedSuppliers, onLoadCategroyTree, supplierSearch } =
		useGoodsBasicInfo()

	const { provinces, getRemoteFrightColumns, provincesInit, addRemoteFright, delRemoteFreight } =
		useGoodsFreightInfo()

	const { isKeyWordAdding, addKeyword } = useGoodsKeywords()

	const { consoleLogSkus, consoleLogAttrs, consoleLogSelectedAttrVs, generateDemoSkus } =
		useGoodsDebug()

	const conf = reactive({
		maxAttrKLen: 3,
		maxAttrVLen: 20,
		maxKeyWordCount: 20,
		maxKeyWordLength: 50,
		longKeyWordTagLength: 20
	})

	const getToAddSkuColumns = () => {
		return [
			{
				title: t('商品详细.上级ID'),
				dataIndex: 'copiedById',
				visible: false
			},
			{
				title: t('商品详细.sort'),
				dataIndex: 'sort',
				batchQuantitySet: true
			},
			{
				title: t('商品详细.cover'),
				dataIndex: 'cover',
				batchImageSet: true
			},
			{
				title: t('商品详细.封面ID'),
				dataIndex: 'coverFileId',
				visible: false
			},
			{
				title: t('商品详细.inventory'),
				dataIndex: 'inventory',
				batchQuantitySet: true
			},
			{
				title: t('商品详细.costPrice'),
				dataIndex: 'costPrice',
				batchPriceSet: true
			},
			{
				title: t('商品详细.commissionPrice'),
				dataIndex: 'commissionPrice',
				batchPriceSet: true
			},
			{
				title: t('商品详细.shopPrice'),
				dataIndex: 'shopPrice',
				batchPriceSet: true
			},
			{
				title: t('商品详细.rewardPrice'),
				dataIndex: 'rewardPrice',
				batchPriceSet: true
			},
			{
				title: t('商品详细.salePrice'),
				dataIndex: 'salePrice',
				batchPriceSet: true
			},
			{
				title: t('商品详细.guidePrice'),
				dataIndex: 'guidePrice',
				batchPriceSet: true
			}
		]
	}

	const getToAddSkuColumnsMap = () => {
		const toAddSkuColumnsMap: Record<string, any> = {}
		getToAddSkuColumns().forEach(item => {
			toAddSkuColumnsMap[item.dataIndex] = item
		})
		return toAddSkuColumnsMap
	}

	const canEditSkuAttrs = ref(true)
	const editForm = ref<typeof initialEditForm>(initialEditForm)

	// 使用模块化的组合式函数
	const {
		skuColumns,
		attrVSelects,
		skuSelects,
		getAttrVSelects,
		generateSkus,
		selVSelSkus,
		changeSelSkus
	} = useGoodsSkuGeneration(editForm, canEditSkuAttrs)

	const {
		addAttrK,
		delAttrK,
		doSaveAttrK,
		addAttrV,
		editAttrV,
		doSaveAttrV,
		delAttrV,
		selAttrV
	} = useGoodsSkuAttributes(editForm, conf)

	const {
		checkBatchSel,
		batchQuantitySet,
		quantityInput,
		batchPriceSet,
		priceInput,
		batchCoverSet,
		batchChangeCover,
		batchCoverDelete
	} = useGoodsSkuBatch(editForm, skuSelects)

	const { doSave } = useGoodsFormSave(editForm)

	// 获取要使用的SPU ID
	const getToUseSpuId = () => {
		if (editForm.value.copiedById) {
			editForm.value.permissionName = '商品库-商品管理-复制商品'
			return editForm.value.copiedById
		}
		if (editForm.value.id) {
			editForm.value.permissionName = '商品库-商品管理-修改商品'
			return editForm.value.id
		}
		return 0
	}

	// 加载相关数据（分类、供应商）
	const loadRelatedData = async (spu: any) => {
		const [categoryRes, supplierRes] = (await Promise.all([
			Api.post('/product/category/select', { chainIds: spu._categoryChainIds }),
			Api.post('/product/supplier/search', { id: spu.supplier_id })
		])) as [ApiResponse, ApiResponse]
		if (categoryRes.list) {
			categoryTree.value = categoryRes.list
		}
		if (supplierRes.list) {
			searchedSuppliers.value = supplierRes.list
		}
	}

	// 填充表单数据
	const fillFormData = (res: ApiResponse) => {
		const { spu } = res
		editForm.value.spu.numbering = spu.numbering
		editForm.value.spu.name = spu.name
		editForm.value.spu.categoryId = spu.category_id
		editForm.value.spu._categoryChainIds = spu._categoryChainIds.split('-')
		editForm.value.spu.supplierId = spu.supplier_id.toString()
		editForm.value.spu.isSecondHand = Enums.common.isDataGetBool(spu.is_second_hand)
		editForm.value.spu.isVirtual = Enums.common.isDataGetBool(spu.is_virtual)
		editForm.value.spu.createdByUser = spu.created_by_user ?? 0
		editForm.value.spu.keywords = spu._keywords ?? []
		editForm.value.salesInfo.sort = spu.sort
		editForm.value.salesInfo.isPutOnSale = Enums.common.isDataGetBool(spu.is_put_on_sale)
		if (spu._putOnSaleRange) {
			editForm.value.salesInfo.putOnSaleRange = [
				dayjs(spu._putOnSaleRange[0], 'YYYY-MM-DD HH:mm'),
				dayjs(spu._putOnSaleRange[1], 'YYYY-MM-DD HH:mm')
			]
		}
		editForm.value.salesInfo.isAutoPutOnSale = Enums.common.isDataGetBool(
			spu.is_auto_put_on_sale
		)
		editForm.value.salesInfo.isAutoPutOffSale = Enums.common.isDataGetBool(
			spu.is_auto_put_off_sale
		)
		editForm.value.freightInfo.freightPrice = spu.freight_price
		editForm.value.freightInfo.remoteFreights = spu._remoteFreights || []
		editForm.value.otherData.isPresentInsurance = Enums.common.isDataGetBool(
			spu.is_present_insurance
		)
	}

	// 处理复制商品逻辑
	const handleCopyGoods = () => {
		canEditSkuAttrs.value = true
		// 清除原商品ID，创建新商品
		editForm.value.id = 0
		// 重置运费模板ID
		editForm.value.freightInfo.remoteFreights.forEach(item => {
			item.id = 0
		})
		// 重置属性ID
		editForm.value.attrs.forEach(item => {
			item.id = 0
			item.v.forEach(vItem => {
				vItem.id = 0
			})
		})
		// 重置SKU ID
		editForm.value.skus.forEach(item => {
			item.copiedById = item.id
			item.id = 0
			item.vIds = item.vIds.map(() => 0)
		})
	}

	// 处理现有商品（编辑或复制）
	const handleExistingGoods = async (spuId: number) => {
		canEditSkuAttrs.value = false
		const formParams = {
			id: spuId,
			permissionName: '商品库-商品管理-商品详细'
		}
		const res = (await Api.post('/product/goods/info', formParams, true)) as ApiResponse
		if (res.spu) {
			await loadRelatedData(res.spu)
			fillFormData(res)
		}
		editForm.value.attrs = res.attrs || []
		editForm.value.skus = res.skus || []
		if (editForm.value.copiedById) {
			handleCopyGoods()
		}
		generateSkus()
	}

	// 加载初始数据
	const loadInitialData = async () => {
		const [categoryRes, supplierRes] = (await Promise.all([
			Api.post('/product/category/select', {}),
			Api.post('/product/supplier/search', {})
		])) as [ApiResponse, ApiResponse]
		if (categoryRes.list) {
			categoryTree.value = categoryRes.list
		}
		if (supplierRes.list) {
			searchedSuppliers.value = supplierRes.list
		}
	}

	// 重置表单数据
	const resetFormData = () => {
		editForm.value.spu.name = ''
		editForm.value.spu.numbering = ''
		editForm.value.spu.categoryId = ''
		editForm.value.spu._categoryChainIds = []
		editForm.value.spu.supplierId = ''
		editForm.value.spu.isSecondHand = false
		editForm.value.spu.isVirtual = false
		editForm.value.spu.createdByUser = 0
		editForm.value.spu.keywords = []
		editForm.value.salesInfo.sort = 0
		editForm.value.salesInfo.isPutOnSale = false
		editForm.value.salesInfo.putOnSaleRange = [] as unknown as [Dayjs, Dayjs]
		editForm.value.salesInfo.isAutoPutOnSale = false
		editForm.value.salesInfo.isAutoPutOffSale = false
		editForm.value.freightInfo.freightPrice = 0
		editForm.value.freightInfo.remoteFreights = []
		editForm.value.otherData.isPresentInsurance = false
		editForm.value.attrs = []
		editForm.value.skus = []
	}

	// 处理新建商品
	const handleNewGoods = async () => {
		await loadInitialData()
		resetFormData()
	}

	// 获取商品基本信息
	const getGoodsInfo = async () => {
		const { id, copiedById } = route.query
		editForm.value.id = Number(id) || 0
		editForm.value.copiedById = Number(copiedById) || 0
		const toUseSpuId = getToUseSpuId()
		if (toUseSpuId) {
			await handleExistingGoods(toUseSpuId)
		} else {
			await handleNewGoods()
		}
	}

	// 监听路由变化，当从编辑跳转到复制时重新获取商品信息
	watch(
		() => route.path,
		(newPath, oldPath) => {
			if (newPath !== oldPath) {
				getGoodsInfo()
			}
		}
	)

	return {
		conf,
		canEditSkuAttrs,
		isKeyWordAdding,
		editForm,
		attrVSelects,
		skuSelects,
		skuColumns,
		categoryTree,
		provinces,
		searchedSuppliers,
		getToAddSkuColumns,
		getToAddSkuColumnsMap,
		getRemoteFrightColumns,
		getGoodsInfo,
		addAttrK,
		delAttrK,
		doSaveAttrK,
		addAttrV,
		editAttrV,
		doSaveAttrV,
		delAttrV,
		selAttrV,
		getAttrVSelects,
		selVSelSkus,
		changeSelSkus,
		generateSkus,
		checkBatchSel,
		batchQuantitySet,
		quantityInput,
		batchPriceSet,
		priceInput,
		batchCoverSet,
		batchChangeCover,
		batchCoverDelete,
		onLoadCategroyTree,
		provincesInit,
		supplierSearch,
		addRemoteFright,
		delRemoteFreight,
		addKeyword,
		consoleLogSkus,
		consoleLogAttrs,
		consoleLogSelectedAttrVs,
		generateDemoSkus,
		doSave
	}
}
